package com.fishsoup.fishweb.component;

import net.javacrumbs.shedlock.core.LockConfiguration;
import net.javacrumbs.shedlock.support.AbstractStorageAccessor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisAccessor extends AbstractStorageAccessor {

    @Autowired
    private RedissonClient redisson;

    @Override
    public boolean insertRecord(LockConfiguration lockConfiguration) {
        RLock lock = redisson.getLock(lockConfiguration.getName());
        try {
            return lock.tryLock(0, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            return false;
        }
    }

    @Override
    public boolean updateRecord(LockConfiguration lockConfiguration) {
        RLock lock = redisson.getLock(lockConfiguration.getName());
        try {
            return lock.tryLock(0, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            return false;
        }
    }

    @Override
    public void unlock(LockConfiguration lockConfiguration) {
        RLock lock = redisson.getLock(lockConfiguration.getName());
        if (lock.isLocked()) {
            lock.unlock();
        }
    }
}
